package com.sheng.project.study.spring.demo04.test1;

import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @author liusheng
 * @date 2023/07/10
 */
@Component
public class MethodBeforeInterceptor implements BeanPostProcessor {
    @Nullable
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        // 在 service1 上面加个拦截器，要求在调用 service1 的任何方法之前需要先输出一行日志
        if ("service1".equals(beanName)) {
            // 代理创建工厂，需传入被代理的目标对象
            ProxyFactory proxyFactory = new ProxyFactory(bean);
            // 添加一个方法前置通知，会在方法执行之前调用通知中的 before 方法
//            proxyFactory.addAdvice((MethodBeforeAdvice) (method, args, target) -> System.out.println("你好,service1"));
            proxyFactory.addAdvice(new MethodBeforeAdvice() {
                @Override
                public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
                    System.out.println("你好,service1");
                }
            });
            // 返回代理对象
            return proxyFactory.getProxy();
        }
        return bean;
    }
}
